package DiannaoShiyongXianzhi;

import java.awt.*;
import java.awt.desktop.AboutHandler;
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.*;
import DiannaoShiyongXianzhi.SheZhi;

public class ShijianGuanli extends JFrame implements ActionListener {
    private static final long serialVersionUID = 1L;
   // private JLabel label;
   // private JTextField textField;
    private JButton button;  //关闭
    private JButton button2;  //初始化
    private JLabel timeLabel;
    private float time;
    private boolean kaiguan;  //开关
    private boolean kaiguan2;  //开关
    
    private JPasswordField passwordField;  
    private Thread thread;
    private JButton closeButton;  //关闭软件
    private SheZhi sheZhi = new SheZhi();
    
    
    
    public ShijianGuanli() {
        super("儿童玩电脑时间限制v1.0");
        setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); // 禁止默认的窗口关闭操作
        //setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(280, 70);
        setLocationRelativeTo(null);
        setResizable(false);

        //label = new JLabel("请输入倒计时时间（秒）：");
        //textField = new JTextField(10);
        button = new JButton("设置");
        button2 = new JButton("初始化");
        button.addActionListener(this);
        button2.addActionListener(this);
        
        /*
        //最小化时窗口设为不
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowIconified(WindowEvent e) {
                setVisible(true);
            }
        });
         */
        
        JPanel panel = new JPanel();
        panel.add(button);
        panel.add(button2);

        // Add a label to display remaining time
        timeLabel = new JLabel("剩余时间：" + time + "秒");
        timeLabel.setForeground(Color.RED);
        panel.add(timeLabel);
        initComponents(panel);
        add(panel);
        //setLocationRelativeTo(null);
        
        
        setUndecorated(true); // 去掉窗口的装饰
//        setExtendedState(JFrame.ICONIFIED); //最小化
        ///getRootPane().setWindowDecorationStyle(JRootPane.NONE);　//采用指定的窗口装饰风格 
        setVisible(true);
        
        
        kaiguan = true;
        kaiguan2 = true;
        actionPerformed2(0);
        
        
    }

    //禁止关闭窗口部分
    private void initComponents(JPanel contentPanel) {
        passwordField = new JPasswordField(10);
        closeButton = new JButton("关闭");  
        closeButton.addActionListener(e -> {
            if (verifyPassword()) {
                setVisible(false);
                dispose();
                System.exit(0);
            } else {
                JOptionPane.showMessageDialog(ShijianGuanli.this, "密码错误!", "Error", JOptionPane.ERROR_MESSAGE);
            }
        });
        //JPanel contentPanel = new JPanel();
        contentPanel.add(new JLabel("输入密码关闭:"));
        contentPanel.add(passwordField);
        contentPanel.add(closeButton);
        add(contentPanel);
    } 
    
    //密码验证
    private boolean verifyPassword() {
        String password = new String(passwordField.getPassword());
        return password.equals(sheZhi.mima); // 此处密码需自定义
    }
    
    //判断时间是否是第二天开始第一次启动软件，是的话需要初始化计时
    private boolean shifouGeri() {
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String formattedDate = dateFormat.format(date);
        System.out.println(formattedDate);	
        boolean shifouxiantong = false;
        
     	try {
    	    FileInputStream input = new FileInputStream("text3.sjxz");
    	    byte[] bytes = new byte[input.available()];
            input.read(bytes);
            String content = new String(bytes);
            shifouxiantong = content.equals(formattedDate.toString());
            input.close();
    	    System.out.println(shifouxiantong);
    	    
    	} catch (IOException e) {
    	    e.printStackTrace();
    	}

        if(shifouxiantong == false) {  //如果不同在输出true的同时，输出今天的日期
	        try (FileOutputStream  out = new FileOutputStream("text3.sjxz")) {
	        	byte[] bytes = formattedDate.getBytes();
	        	
	        	out.write(bytes);
	        } catch (IOException ex) {
	            ex.printStackTrace();
	        }
    	
        }

    	return shifouxiantong;
    }
    
    //判断是否在使用时间内
    private boolean shifouzaiShijiannai() {
        Date date = new Date();
        SimpleDateFormat timeFormat = new SimpleDateFormat("HH.mm");
        String formattedTime = timeFormat.format(date);
        System.out.println(formattedTime);
        float dqsj = Float.valueOf(formattedTime.toString());
        boolean panduan = sheZhi.shezhicanshu[0]<dqsj && dqsj<sheZhi.shezhicanshu[1];
        System.out.println(panduan);
    	return panduan;
    	
    }
    
    //计时部分
    public void actionPerformed2(int leixing) {
        
    	if(shifouzaiShijiannai() == false) {
    		
        	pack();  //启动就最大化
        	setAlwaysOnTop(true); // 设置窗口为置顶窗口
        	setExtendedState(JFrame.MAXIMIZED_BOTH); // 最大化窗口
        	timeLabel.setText("现在还不能用哟！剩余时间：" + sheZhi.shezhicanshu[2] + "秒");
        	dingshiGuanji();
    		return;
    	} 
    	
    	if(kaiguan) {
	    	try {
//	            time = Integer.parseInt(textField.getText());
	            thread = new Thread(new Runnable() {
	                public void run() {
	                    try {
	                        kaiguan = false;
	                        if(leixing == 0) {
		                        //读取上次时间
                            	try {
                            	    FileInputStream fileInputStream = new FileInputStream("text2.sjxz");
                            	    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
                            	    String line;
                            	    //int ii = 0;
                            	    while ((line = bufferedReader.readLine()) != null) {
                            	    	//shezhicanshu2[ii]= line;
                            	    	Float lsblFloat = Float.valueOf(line);
                            	    	//shezhicanshu[ii]= lsblFloat;
                            	    	System.out.println(lsblFloat);
                            	    	//System.out.println(line);
                            	    	//ii++;
                            	    	time = lsblFloat;
                            	    }
                            	    bufferedReader.close();
                            	    fileInputStream.close();
                            	    
                            	} catch (IOException e) {
                            	    e.printStackTrace();
                            	}
	                            	
	                        	if(time == 0) {time = 10;}	
	                        	
	                        }else {
	                            
		                        if(leixing == 1) {  // 初始化按钮
				                        //初始化时间
		                            	time = (int) sheZhi.shezhicanshu[2];
		                            }
		                        }   
	                        
	                        if(shifouGeri() == false) {  // 或者为第二日第一次启动
		                        //初始化时间
                            	time = (int) sheZhi.shezhicanshu[2];
                            }
	                        
                        	//开始计时
	                        Thread.sleep(1100);
	                        if(kaiguan2 == false) {kaiguan2 = true;}
	                    	for (float i = time; i >= 0 && kaiguan2; i--) {
	                            timeLabel.setText("剩余时间：" + i + "秒");
	                            try (FileOutputStream  out = new FileOutputStream("text2.sjxz")) {
	                            	byte[] bytes = String.valueOf(i).getBytes();
	                                out.write(bytes);
	                            	//out.write(i & 0xFF);  //只能输出两位数
	                            } catch (IOException ex) {
	                                ex.printStackTrace();
	                            }
	                            Thread.sleep(1000);
	                        }
	                        kaiguan = true;
	                        if(kaiguan2) {
	                        	pack();  //启动就最大化
	                        	setAlwaysOnTop(true); // 设置窗口为置顶窗口
	                        	setExtendedState(JFrame.MAXIMIZED_BOTH); // 最大化窗口
	                        	//setResizable(false); // 禁用调整窗口大小
	                        	dingshiGuanji();
	                        }
	                    } catch (Exception e) {
	                        e.printStackTrace();
	                    }
	                }
	            });
	            
	            thread.start();
	        } catch (NumberFormatException ex) {
	            JOptionPane.showMessageDialog(null, "请输入数字！");
	        }

        }
        	
        
    }
    
    //定时关机
    public void dingshiGuanji() {
    	try {
            thread = new Thread(new Runnable() {
                @SuppressWarnings("deprecation")
				public void run() {
                    try {
                        
                    	//开始计时
                    	for (float i = 300; i >= 0 && kaiguan2; i--) {
                            timeLabel.setText("准备关机：" + i + "秒");
                            Thread.sleep(1000);
                        }
                    	// 延时 5 分钟后关机
                        String command = "shutdown -s -t 5";
                        Runtime.getRuntime().exec(command);
                        JOptionPane.showMessageDialog(ShijianGuanli.this, "准备关机了!", "Error", JOptionPane.ERROR_MESSAGE);
                        
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            
            thread.start();
        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(null, "请输入数字！");
        } 	
        
    }
       
    //设置与初始化
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == button) {
        	
            if (verifyPassword()) {
                sheZhi.daKai();  //启动设置窗口
                //dispose();  //关闭本窗口
            } else {
                JOptionPane.showMessageDialog(ShijianGuanli.this, "密码错误!", "Error", JOptionPane.ERROR_MESSAGE);
            }
        }
        if (e.getSource() == button2) {
        	
            if (verifyPassword()) {
            	kaiguan = true;  //允许建立新线程
            	kaiguan2 = false;  //停止上一个线程
            	actionPerformed2(1);  //重新初始化为设置时间启动锁屏线程
            	//setExtendedState(Frame.ICONIFIED);  //最小化窗口
                System.out.println("初始化成功");
            } else {
                JOptionPane.showMessageDialog(ShijianGuanli.this, "密码错误!", "Error", JOptionPane.ERROR_MESSAGE);
            }        	
        	
        }
        
    }

  
    public static void main(String[] args) {
    	/*
    	try {
    	    FileInputStream fileInputStream = new FileInputStream("text2.txt");
    	    int line;
    	    line = fileInputStream.read();
    	    System.out.println(line);
    	    
    	    fileInputStream.close();
    	    
    	} catch (IOException e) {
    	    e.printStackTrace();
    	}
*/
        new ShijianGuanli();
        //System exit;
    }
  
    
}


